// pages/add_custom/add_custom.js
const app = getApp()
const moment = require('../../utils/moment.js');
Page({
  data: {
    customName: ''
  },
  bindValue: function (e) {
    this.setData({
      customName: e.detail.value
    })
  },
  saveCustom: function (e) {
    let customName = this.data.customName
    // 读取缓存中已有的习惯列表
    let customList = []
    app.apis().getCustoms(app.globalData.userObject.id).then(function (data) {
      customList = data._embedded.custom

      let existe = false
      customList.forEach(item => {
        if (item.name === customName) existe = true
      })

      if (existe) {
        wx.showModal({
          title: '提示',
          content: '习惯"' + customName + '"已经存在，不能重复添加！',
          showCancel: false,
          confirmText: '确定',
          success: function () {
            wx.switchTab({
              url: '../custom_punch/custom_punch'
            })
          }
        })
      } else {
        // 添加新习惯
        let today = moment().format('YYYY-MM-DD')
        Promise.all([
          app.apis().addCustom(app.globalData.userObject.id, customName),
          app.apis().addCustomLog(app.globalData.userObject.id, today, customName)
        ]).then(function () {
          wx.showModal({
            title: '提示',
            content: '新习惯"' + customName + '"添加成功！',
            showCancel: false,
            confirmText: '确定',
            success: function () {
              wx.switchTab({
                url: '../custom_punch/custom_punch'
              })
            }
          })
        })
      }
    })
  }
})